package com.zsrt.day20170410.pm;

import java.util.Scanner;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.zsrt.utils.ArrayUtil;

/**
*@author jzh
*@创建时间 2017年4月10日下午2:17:43
*类说明：
*/
public class ArrayCRUD {
	private String[] class1704={"贾梦菊","靳志辉","何小强","罗智壕","张嘉源"};	
	private Scanner in=null;
	
	@Before
	public void before(){
		in=new Scanner(System.in);
	}
    @After
    public void after(){
    	in.close();
	}
	/**
	 * 增加
	 * @throws Exception
	 */
	@Test
	public void addTest() throws Exception {
		System.out.println("输入学生名字：");
        String name=in.next();
        
		add(class1704,name);
		ArrayUtil.printArray(class1704);
		
	}
	public void add(String[] array,String newName){
        int xb = checkStudentByName(class1704,newName);
        if(xb>=0){
        	System.out.println("该学生已存在");
        }else{
        	String[] newArray=new String[array.length+1];
        	for(int i=0;i<class1704.length;i++){
        		newArray[i]=class1704[i];
            }
        	newArray[class1704.length]=newName;
        	class1704=newArray;
        }     
	}
	/**
	 * 更改
	 * @throws Exception
	 */
	@Test
	public void changeStudentByNameTest() throws Exception {
		
		in.nextLine();
		
		String oldName="贾梦菊";
		String newName="贾宝玉";		
		changeStudentByName(class1704,oldName,newName);
	}
	public void changeStudentByName(String[] array,String oldName,String newName){
		int xb = checkStudentByName(class1704,oldName);
		if(xb<0){
			System.out.println("要查找的学生不存在");
		}else{
			array[xb]=newName;
			ArrayUtil.printArray(array);
		}
	}
	/**
	 * 查找
	 * @param name
	 * @return
	 */
	public int checkStudentByName(String[] array,String name) {
		int  xb=-1;
		for(int i=0;i<array.length;i++){
        	if(name.equals(array[i])){
        		return i;
        	}
        }
		return xb;
	}
	/**
	 * 删除
	 * @param array
	 * @param name
	 */
	@Test
	public void deleteStudentByNameTest() throws Exception {
		String name="贾梦菊";
		deleteStudentByName(class1704,name);
		ArrayUtil.printArray(class1704);
	}
	public void deleteStudentByName(String[] array,String name){
		int xb = checkStudentByName(array,name);
		if(xb<0){
			System.out.println("要查找的学生不存在");
		}else{
			String[] newArray=new String[array.length-1];
		    for(int i=0;i<xb;i++){
		    	newArray[i]=array[i];
		    }
		    for(int i=xb+1;i<array.length;i++){
		    	newArray[i-1]=array[i];
		    }
		    class1704=newArray;
		}
		
		
	}

}
